#include "common.h"

/* This callback handler should be implemented by users for their custom logic */
static int async_cb_handler(Task *task)
{
    int i;
    Upstream **up;
    int rc;
    int again = 0;
    Memcache *mc;
    
    ds_array_s *array = task->upstreams;
    up = ((Upstream**)array->elts);
    task->conn->write->handler = WriteClientBuf;

    for (i = 0; i < array->nelts; i++) {
        mc = up[i]->data;
        if (mc->value.len != 0) {
           	AppendResponseBuf(task->conn,mc->value.data,mc->value.len);
        }
        else {
            AppendResponseBuf(task->conn,"Not Exist ",10);
        } 
    }
    SendHttpBody(task->conn,0);
    
    return 0;
}

int mod_num_handler(Conn *c)
{
    int rc;
    Upstream *up;
    String str;
    
    if (CreateTaskTable(c,async_cb_handler) == NULL) {
        Log_Write(g_server->log, "HttpHandler: CreateTaskTable Failed");
	    c->err = 1;
        FinalizeConn(c);	
	    return 1;
    }
    
    up = CreateUpsteam(c->task, UPSTREAM_PROTOCAL_MC, "60.28.113.121",12000);
    if (up == NULL) {
        Log_Write(g_server->log, "HttpHandler: CreateUpstream Failed");
	    c->err = 1;
        FinalizeConn(c);	
	    return 1;
    }
    str.data = "111";
    str.len = 3;
    if (MC_AddCommand(up, MC_GET_METHOD, &str) != HTTP_OK) {
        Log_Write(g_server->log, "HttpHandler: Add Upstream Request Buf Failed");
        c->err = 1;
        FinalizeConn(c);
	    return 1;    
    }
    if (AddTask(up,c->task) != HTTP_OK) {
        Log_Write(g_server->log, "HttpHandler: Add Task Failed");
	    c->err = 1;
        FinalizeConn(c);    
	    return 1;
    }


    up = CreateUpsteam(c->task, UPSTREAM_PROTOCAL_MC, "60.28.113.121",12001);
    if (up == NULL) {
        Log_Write(g_server->log, "HttpHandler: CreateUpstream Failed");
        c->err = 1;
        FinalizeConn(c);
        return 1;
    }
    str.data = "111";
    str.len = 3;
    if (MC_AddCommand(up, MC_GET_METHOD, &str) != HTTP_OK) {
        Log_Write(g_server->log, "HttpHandler: Add Upstream Request Buf Failed");
        c->err = 1;
        FinalizeConn(c);
        return 1;
    }
    if (AddTask(up,c->task) != HTTP_OK) {
        Log_Write(g_server->log, "HttpHandler: Add Task Failed");
        c->err = 1;
        FinalizeConn(c);
        return 1;
    }

    RunTaskEngine(c->task);
}